package net.lab1024.smartdb.springboot.service;

import net.lab1024.smartdb.SmartDb;
import net.lab1024.smartdb.springboot.domain.entity.UserEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 读写分离 demos
 *
 * @author zhuoda
 */

@Service
public class ReadWriteService {

    /**
     * 主、从数据库
     */
    @Resource(name = "default")
    private SmartDb smartDb;


    /**
     * 读取从库
     *
     * @return
     */
    public List<UserEntity> readSlave() {
        /**
         * 此smartdb种包含了master和slave.
         * 默认所有的 read操作，都是在slave数据源执行的
         */
        List<UserEntity> list = smartDb.selectSqlBuilder()
                .select("*")
                .from(UserEntity.class)
                .queryList(UserEntity.class);

        return list;
    }

    /**
     * 读取主库
     *
     * @return
     */
    public List<UserEntity> readMaster() {
        /**
         * 此smartdb种包含了master和slave.
         * getMaster()方法，获取的是master数据源，然后再该数据源上执行sql
         */
        List<UserEntity> list = smartDb.getMaster().selectSqlBuilder()
                .select("*")
                .from(UserEntity.class)
                .queryList(UserEntity.class);

        return list;
    }


}
